<?php

namespace app\wechat\controller;

use app\admin\model\Authorizer;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\HttpException;
use think\facade\Cache;

// 第三方平台
class Platform
{

    public $platform;

    public function __construct()
    {
        $this->platform = Factory::openPlatform(config('wechat.open_platform.default'));
    }

    // 获取第三方平台实例
    public function getPlatform()
    {
        return $this->platform;
    }

    // 获取公众号实例
    public function getGh($appid)
    {
        $refresh_token = Authorizer::where(['appid' => $appid])->value('refresh_token');
        $gh = $this->platform->officialAccount($appid, $refresh_token);
        return $gh;
    }

    public function getGhWithToken($appid, $refresh_token)
    {
        $gh = $this->platform->officialAccount($appid, $refresh_token);
        return $gh;
    }

    public function getGhToken($appid)
    {
        $gh = $this->getGh($appid);
        $token = $gh->access_token->getToken();
        return $token;
    }

    // 无数据库操作获取公众号access_token
    // 并自行保存一份在cache中
    public function get_gh_token_no_db($appid, $refresh_token)
    {
        try {
            $gh = $this->platform->officialAccount($appid, $refresh_token);
            $token = $gh->access_token->getToken(true);
            Cache::set('access_token' . $appid, $token['authorizer_access_token'], '7000');
            return $token['authorizer_access_token'];
        } catch (HttpException $exception) {
            return false;
        }
    }
}
